<template>
  <div class="dowebok">
    <div class="container">
      <div class="left">
        <div class="login">登陆</div>
        <div class="eula">欢迎来到iot云平台，请输入您的学号和密码以登录！</div>
        <div class="adminswitch" style="margin-bottom:20px;" @click="adminSwitch">{{ texttips }}</div>
        <div v-if="roleCardShow" class="roleCard">
          <el-carousel type="card" :interval="5000" :autoplay="isAutoplay" height="120px" @change="getFocuRole">
            <el-carousel-item v-for="(item, i) in roleListMsg" :key="i" :style="'background:#474'+i+'59'">
              <span class="carouseltips">{{ item.tips }}</span>
              <h3 class="medium">{{ item.rolename }}</h3>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div class="right">
        <div class="form">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
            <el-form-item class="avatarbox">
              <el-image :src="avatar?`http://124.222.15.71:8191/api/hold/imgdownload?fileName=${avatar}`:normalAvatar" fit="fill" :lazy="true" class="user-avatar" />
            </el-form-item>
            <el-form-item prop="studentid">
              <svg-icon icon-class="user" />
              <el-input
                ref="studentid"
                v-model="loginForm.studentid"
                placeholder="账号"
                name="studentid"
                type="text"
                tabindex="1"
                auto-complete="on"
                @blur="getAvatarAtLogin()"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="密码"
                name="password"
                tabindex="2"
                auto-complete="on"
                @keyup.enter.native="handleLogin"
              />
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" @click="showPwd" />
            </el-form-item>

            <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>
          </el-form>
        </div>
        <div class="register">
          <div class="registerbox">
            <span class="adminswitch" @click="openDrawer('新用户注册')">新用户注册</span>
            <span class="adminswitch" @click="openDrawer('找回密码')">忘记密码？</span>
          </div>
        </div>
      </div>
      <el-drawer
        :wrapper-closable="false"
        :title="drawerTitle"
        :visible.sync="drawer"
        direction="rtl"
        size="50%"
        :destroy-on-close="true"
      >
        <add-user v-if="drawerTitle==='新用户注册'" @closeDrawer="closeDrawer" />
        <div v-else style="height:100%;padding:0 20px;">
          <el-card style="height:70%;">
            <el-form ref="findForm" :model="findForm" :rules="loginRules">
              <el-form-item v-if="!hasFind" prop="studentname" label="姓名">
                <el-input
                  v-model="findForm.studentname"
                />
              </el-form-item>
              <el-form-item v-if="!hasFind" prop="studentid" label="学号">
                <el-input
                  v-model="findForm.studentid"
                />
              </el-form-item>

              <el-form-item v-if="hasFind" prop="password" label="新密码">
                <el-input
                  v-model="findForm.password"
                />
              </el-form-item>
              <el-form-item class="loginregister">
                <el-button type="primary" @click="onEditSubmit">提交</el-button>
                <el-button @click="closeDrawer">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex' // 引入vuex的辅助函数
import AddUser from '../users/components/add-user.vue'
import { findUser, editUser, getAllUser } from '@/api/user'

export default {
  name: 'Login',
  components: {
    AddUser
  },
  data() {
    const validateStudentid = (rule, value, callback) => {
      if (value.length < 6 || value.length > 12) {
        callback(new Error('用户学号长度不小于6'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('用户密码不少于四位数，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      texttips: '>>点击试用不同角色账号<<',
      isAutoplay: false,
      roleCardShow: false,
      roleListMsg: [
        {
          rolename: '普通用户',
          password: '123456',
          studentid: 'admin2023',
          tips: 'NormalUser'
        },
        {
          rolename: '设备管理员',
          password: '123456',
          studentid: 'admin2023',
          tips: 'EquipsManager'
        },
        {
          rolename: '组织架构管理员',
          password: '123456',
          studentid: 'admin2023',
          tips: 'StructureManager'
        },
        {
          rolename: '用户管理员',
          password: '123456',
          studentid: 'admin2023',
          tips: 'UsersManager'
        },
        {
          rolename: '角色管理员',
          password: '123456',
          studentid: 'admin20235',
          tips: 'RolesManager'
        },
        {
          rolename: '权限管理员',
          password: '123456',
          studentid: 'admin2023',
          tips: 'RightsManager'
        },
        {
          rolename: '超级管理员',
          password: '123456',
          studentid: 'admin2023',
          tips: 'Leader'
        }
      ],
      avatar: '',
      normalAvatar: require('@/assets/无用户.png'),
      drawerTitle: '注册新用户',
      drawer: false,
      loginForm: {
        studentid: '',
        password: ''
      },
      findForm: {
        studentid: '',
        password: '',
        studentname: ''
      },
      findUserInfo: {},
      loginRules: {
        studentname: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        studentid: [{ required: true, trigger: 'blur', validator: validateStudentid }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      hasFind: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions(['user/login']),
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(async isOK => {
        if (isOK) {
          try {
            this.loading = true
            // 只有校验通过了 我们才去调用action
            // this.$store.commit('user/setUserId', this.loginForm.studentid)
            // this['user/setUserId'](this.loginForm.studentid)
            await this['user/login'](this.loginForm)
            // 应该登录成功之后
            // async标记的函数实际上一个promise对象
            // await下面的代码 都是成功执行的代码
            this.$router.push('/')
          } catch (error) {
            // console.log(error)
          } finally {
            //  不论执行try 还是catch  都去关闭转圈
            this.loading = false
          }
        }
      })
    },
    openDrawer(title) {
      this.drawerTitle = title
      this.drawer = true
    },
    closeDrawer() {
      const findForm = this.findForm
      for (const i in findForm) {
        findForm[i] = ''
      }
      this.findForm = findForm
      this.findUserInfo = {}
      this.drawer = false
      this.hasFin = false
    },
    async findUser() {
      try {
        this.findUserInfo = await findUser(this.findForm)
        this.hasFind = true
      } catch (error) {
        // console.log(error)
      }
    },
    onEditSubmit() {
      this.$refs.findForm.validate(async isOK => {
        if (isOK) {
          if (this.hasFind) {
            this.findUserInfo.password = this.findForm.password
            this.$confirm('确定要更改该用户密码吗').then(() => {
            // 如果点击了确定就会进入then
              return editUser(this.findUserInfo.studentid, this.findUserInfo)
            }).then(() => {
              this.$message.success('更改成功')
              this.closeDrawer()
            })
          } else {
            this.findUser()
          }
        }
      })
    },
    async getAvatarAtLogin() {
      const id = this.loginForm.studentid
      const { rows } = await getAllUser(1, 99, { studentid: id })
      if (rows.length !== 0) {
        this.avatar = rows[0].photo
      } else {
        this.avatar = ''
      }
    },
    adminSwitch() {
      this.texttips = this.texttips === '>>点击试用不同角色账号<<' ? '>> 确认 <<' : '>>点击试用不同角色账号<<'
      this.roleCardShow = !this.roleCardShow
      if (this.roleCardShow) {
        this.loginForm.studentid = 'admin2023'
        this.loginForm.password = '123456'
        this.getAvatarAtLogin()
      }
    },
    getFocuRole(val) {
      this.loginForm.studentid = this.roleListMsg[val].studentid
      this.loginForm.password = this.roleListMsg[val].password
      this.getAvatarAtLogin()
    }
  }
}
</script>

<style lang="scss" scoped>
::selection {
  background: #2d2f36;
}

::-webkit-selection {
  background: #2d2f36;
}

::-moz-selection {
  background: #2d2f36;
}

body {
  background: white;
  font-family: 'Inter UI', sans-serif;
  margin: 0;
  padding: 20px;

}

.dowebok {
  background: #e2e2e5;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: absolute;
  place-content: center;
  width: 100%;
}

@media (max-width: 767px) {
  .dowebok {
    height: 100%;
  }
}

.container {
  display: flex;
  height: 500px;
  margin: 0 auto;
  width: 800px;
}

@media (max-width: 767px) {
  .container {
    flex-direction: column;
    height: 630px;
    width: 320px;
  }
}

.left {
  background: white;
  height: calc(100% - 40px);
  top: 20px;
  position: relative;
  width: 50%;
}

@media (max-width: 767px) {
  .left {
    height: 100%;
    left: 20px;
    width: calc(100% - 40px);
    max-height: 270px;
  }
}

.login {
  font-size: 50px;
  font-weight: 900;
  margin: 100px 40px 40px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, 0.22);
}

.eula {
  color: #999;
  font-size: 14px;
  line-height: 1.5;
  margin: 40px;
}

.right {
  background: #474a59;
  box-shadow: 0px 0px 40px 16px rgba(0, 0, 0, 0.22);
  color: #f1f1f2;
  position: relative;
  width: 50%;
}

@media (max-width: 767px) {
  .right {
    flex-shrink: 0;
    height: 100%;
    width: 100%;
    max-height: 350px;
  }
}

svg {
  position: absolute;
  width: 320px;
}

path {
  fill: none;
  stroke: url(#linearGradient);
  stroke-width: 4;
  stroke-dasharray: 240 1386;
}

.form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

label {
  color: #c2c2c5;
  display: block;
  font-size: 14px;
  height: 16px;
  margin-top: 20px;
  margin-bottom: 5px;
}

input {
  background: transparent;
  border: 0;
  color: #f2f2f2;
  font-size: 20px;
  height: 40px;
  line-height: 30px;
  outline: none !important;
  width: 100%;
}

input::-moz-focus-inner {
  border: 0;
}

#submit {
  color: #707075;
  margin-top: 40px;
  transition: color 300ms;
}

#submit:focus {
  color: #f2f2f2;
}

#submit:active {
  color: #d0d0d2;
}
.svg-icon{
  top: 10px;
  right:-20px;
  cursor: pointer;
}
.register{
  font-size: 12px;
  width: 100%;
  position: absolute;
  color: #999;
  bottom: 0px;
  padding: 10px;
  .registerbox{
    display: flex;
    justify-content: space-between;
    span{
      cursor: pointer;
    }
  }
}
.avatarbox{
  text-align: center;
  .user-avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    border: 1px solid white;
    box-shadow: 3px 10px 10px rgba(0, 0, 0, 0.22);
    background: #fff;
    margin-bottom: -20px;
  }
}
.adminswitch{
  text-align: center;
  color: #999;
  font-size: 14px;
  line-height: 1.5;
  cursor: pointer;
}
.adminswitch:hover{
  color: #409EFF;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.22);
}
</style>
